/*
 * comlan
 */

package com.promfy.service.log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

/**
* log service, log will save in packageName/files/log/xxx.log
* 1.it will create log file every day.
* 2.it will delete log file 7's earlier.
* @author mfy
*/
public class LogService extends Service {
        private static final String TAG = "LogService";
      
        /** 
         * max size of log file. 
         * if size it bigger, it will create a new log file 
         */
        private static final int MEMORY_LOG_FILE_MAX_SIZE =  10 * 1024 * 1024;  
      
        /** 
         * duration time to check size of log file
         */
        private static final int MEMORY_LOG_FILE_MONITOR_INTERVAL = 10 * 60 * 1000;        
        
        /**
         * days to keep log file, 
         * older file will be deleted.
         */
        private static final int SDCARD_LOG_FILE_SAVE_DAYS = 7;                        
        
        /**
         * path of log file
         */
        private String LOG_PATH_MEMORY_DIR;     
        
        /**
         * path of this service classs, it can record service exception 
         */
        @SuppressWarnings("unused")
        private String LOG_SERVICE_LOG_PATH;        //本服务产生的日志，记录日志服务开启失败信息
        
        /**
         * type of saving log.
         */
        private final int MEMORY_TYPE = 1;                        
        private int CURR_LOG_TYPE = MEMORY_TYPE;       
        
        private String CURR_INSTALL_LOG_NAME;       
        
        /**
         * file name of this service
         */
        private String logServiceLogName = "Log.log";
        private SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        private OutputStreamWriter writer; 
        
        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HHmmss");
        
        private Process process;
        
        private WakeLock wakeLock;  
        
        private LogTaskReceiver logTaskReceiver; 
        
        /**
         * listen size of log file, in order to make new log file.
         */
        private boolean logSizeMoniting = false;                
        
        /**
         * action
         */
        private static String MONITOR_LOG_SIZE_ACTION = "MONITOR_LOG_SIZE";               
        /**
         * action
         */
        private static String SWITCH_LOG_FILE_ACTION = "SWITCH_LOG_FILE_ACTION";       
        
        @Override
        public IBinder onBind(Intent intent) {
                return null;
        }

        @Override
        public void onCreate() {
                super.onCreate(); 
                init();
                register();
                deploySwitchLogFileTask();        
                new LogCollectorThread().start();
        }
        
        private void init(){
                LOG_PATH_MEMORY_DIR = getFilesDir().getAbsolutePath() + File.separator + "log";
                LOG_SERVICE_LOG_PATH = LOG_PATH_MEMORY_DIR + File.separator + logServiceLogName;
              
                createLogDir();
               
                PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
                wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
                
                CURR_LOG_TYPE = getCurrLogType();
                Log.i(TAG, "LogService onCreate");
        }
        
        private void register(){
			IntentFilter logTaskFilter = new IntentFilter();
			logTaskFilter.addAction(MONITOR_LOG_SIZE_ACTION);
			logTaskFilter.addAction(SWITCH_LOG_FILE_ACTION);
			logTaskReceiver = new LogTaskReceiver();
			registerReceiver(logTaskReceiver, logTaskFilter);
        }
        
        
        
        /**
         * get current log type,(where to save log files.)
         * @return
         */
        public int getCurrLogType(){
        	return MEMORY_TYPE;
        }

        /**
         * alarm to make new log file,
         * it happens every single day now.
         */
        private void deploySwitchLogFileTask() {
                Intent intent = new Intent(SWITCH_LOG_FILE_ACTION);
                PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);

                AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
                recordLogServiceLog("deployNextTask succ,next task time is:"+myLogSdf.format(calendar.getTime()));
        }

        /**
         * new thread to collect log file
         * 1. clear log cache in logcat
         * 2. kill logcat process which belongs to itself, in order to avoid multi process recording one log file.
         * 3. start log collect thread
         * 4. deal log file
         */ 
        class LogCollectorThread extends Thread {
                
                public LogCollectorThread(){
                        super("LogCollectorThread");
                        Log.d(TAG, "LogCollectorThread is create");
                }
                
                @Override
                public void run() {
                        try {
                                wakeLock.acquire();      
                                
                                clearLogCache();
                                
                                List<String> orgProcessList = getAllProcess();
                                List<ProcessInfo> processInfoList = getProcessInfoList(orgProcessList);
                                killLogcatProc(processInfoList);
                                
                                createLogCollector();
                                
                                Thread.sleep(1000);//sleep, make new file, and deal it; otherwise it can't be deleted because of new file dosen't exist
                                
                                handleLog();
                                
                                wakeLock.release();        
                        } catch (Exception e) {
                                e.printStackTrace();
                                recordLogServiceLog(Log.getStackTraceString(e));
                        }
                }
        }
        
        /**
         * clear log cache, avoiding redundancy log in a log file.
         */
        private void clearLogCache() {
                Process proc = null;
                List<String> commandList = new ArrayList<String>();
                commandList.add("logcat");
                commandList.add("-c");
                try {
                        proc = Runtime.getRuntime().exec(
                                        commandList.toArray(new String[commandList.size()]));
                        StreamConsumer errorGobbler = new StreamConsumer(proc
                                        .getErrorStream());

                        StreamConsumer outputGobbler = new StreamConsumer(proc
                                        .getInputStream());

                        errorGobbler.start();
                        outputGobbler.start();
                        if (proc.waitFor() != 0) {
                                Log.e(TAG, " clearLogCache proc.waitFor() != 0");
                                recordLogServiceLog("clearLogCache clearLogCache proc.waitFor() != 0");
                        }
                } catch (Exception e) {
                        Log.e(TAG, "clearLogCache failed", e);
                        recordLogServiceLog("clearLogCache failed");
                } finally {
                        try {
                                proc.destroy();
                        } catch (Exception e) {
                                Log.e(TAG, "clearLogCache failed", e);
                                recordLogServiceLog("clearLogCache failed");
                        }
                }
        }

        /**
         * kill logcat process which belongs to itself
         * if it have multi logcat process, it will cause redundancy log in a log file.
         * @param allProcList
         * @return
         */
        private void killLogcatProc(List<ProcessInfo> allProcList) {
                if(process != null){
                        process.destroy();
                }
                String packName = this.getPackageName();
                String myUser = getAppUser(packName, allProcList);
 
                for (ProcessInfo processInfo : allProcList) {
                        if (processInfo.name.toLowerCase().equals("logcat")
                                        && processInfo.user.equals(myUser)) {
                                android.os.Process.killProcess(Integer
                                                .parseInt(processInfo.pid));
                               
                        }
                }
        }

        /**
         * get user of of this process.
         * @param packName
         * @param allProcList
         * @return
         */
        private String getAppUser(String packName, List<ProcessInfo> allProcList) {
                for (ProcessInfo processInfo : allProcList) {
                        if (processInfo.name.equals(packName)) {
                                return processInfo.user;
                        }
                }
                return null;
        }

        /**
         * get PID, User, name by ps command
         * @param orgProcessList
         * @return
         */
        private List<ProcessInfo> getProcessInfoList(List<String> orgProcessList) {
                List<ProcessInfo> procInfoList = new ArrayList<ProcessInfo>();
                for (int i = 1; i < orgProcessList.size(); i++) {
                        String processInfo = orgProcessList.get(i);
                        String[] proStr = processInfo.split(" ");
                        // USER PID PPID VSIZE RSS WCHAN PC NAME
                        // root 1 0 416 300 c00d4b28 0000cd5c S /init
                        List<String> orgInfo = new ArrayList<String>();
                        for (String str : proStr) {
                                if (!"".equals(str)) {
                                        orgInfo.add(str);
                                }
                        }
                        if (orgInfo.size() == 9) {
                                ProcessInfo pInfo = new ProcessInfo();
                                pInfo.user = orgInfo.get(0);
                                pInfo.pid = orgInfo.get(1);
                                pInfo.ppid = orgInfo.get(2);
                                pInfo.name = orgInfo.get(8);
                                procInfoList.add(pInfo);
                        }
                }
                return procInfoList;
        }

        /**
         * get process inf by ps command
         * 
         * @return
         *                         USER PID PPID VSIZE RSS WCHAN PC NAME
         *                         root 1 0 416 300 c00d4b28 0000cd5c S /init
         */
        private List<String> getAllProcess() {
                List<String> orgProcList = new ArrayList<String>();
                Process proc = null;
                try {
                        proc = Runtime.getRuntime().exec("ps");
                        StreamConsumer errorConsumer = new StreamConsumer(proc
                                        .getErrorStream());

                        StreamConsumer outputConsumer = new StreamConsumer(proc
                                        .getInputStream(), orgProcList);

                        errorConsumer.start();
                        outputConsumer.start();
                        if (proc.waitFor() != 0) {
                                Log.e(TAG, "getAllProcess proc.waitFor() != 0");
                                recordLogServiceLog("getAllProcess proc.waitFor() != 0");
                        }
                } catch (Exception e) {
                        Log.e(TAG, "getAllProcess failed", e);
                        recordLogServiceLog("getAllProcess failed");
                } finally {
                        try {
                                proc.destroy();
                        } catch (Exception e) {
                                Log.e(TAG, "getAllProcess failed", e);
                                recordLogServiceLog("getAllProcess failed");
                        }
                }
                return orgProcList;
        }
        
        /**
         * create log collector by logcat command.
         */
        public void createLogCollector() {
                String logFileName = sdf.format(new Date()) + ".log";
                List<String> commandList = new ArrayList<String>();
                commandList.add("logcat");
                commandList.add("-f");
                commandList.add(getLogPath());
                commandList.add("-v");
                commandList.add("time");
                commandList.add("*:V");
                
                try {
                        process = Runtime.getRuntime().exec(
                                        commandList.toArray(new String[commandList.size()]));
                        recordLogServiceLog("start collecting the log,and log name is:"+logFileName);
                        // process.waitFor();
                } catch (Exception e) {
                        Log.e(TAG, "CollectorThread == >" + e.getMessage(), e);
                        recordLogServiceLog("CollectorThread == >" + e.getMessage());
                }
        }
        
        /**
         * get absolutely path of log.
         * @return
         */
        public String getLogPath(){
                createLogDir();
                String logFileName = sdf.format(new Date()) + ".log";
                        CURR_INSTALL_LOG_NAME = logFileName;
                        Log.d(TAG, "Log stored in memory, the path is:"+LOG_PATH_MEMORY_DIR + File.separator + logFileName);
                        return LOG_PATH_MEMORY_DIR + File.separator + logFileName;

        }
        
        /**
         * deal log file
         * 1.deploy log size monitor task.
         * 2.delete expired log files.
         */
        public void handleLog(){
                        deployLogSizeMonitorTask();
                        deleteMemoryExpiredLog();

        }
        
        /**
         * deploy log size monitor task.
         */
        private void deployLogSizeMonitorTask() {
                if(logSizeMoniting){       
                        return;
                }
                logSizeMoniting = true;
                Intent intent = new Intent(MONITOR_LOG_SIZE_ACTION);
                PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
                AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), MEMORY_LOG_FILE_MONITOR_INTERVAL, sender);
                Log.d(TAG, "deployLogSizeMonitorTask() succ !");
        }
        
        /**
         * cancel log size monitor task.
         */  
        private void cancelLogSizeMonitorTask() {
                logSizeMoniting = false;
                AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                Intent intent = new Intent(MONITOR_LOG_SIZE_ACTION);
                PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
                am.cancel(sender);
                
                Log.d(TAG, "canelLogSizeMonitorTask() succ");
        }
        
        /**

         * check if size of log file is bigger than standard size.
         * if bigger, create a new log collector thread.
         */
        private void checkLogSize(){
                if(CURR_INSTALL_LOG_NAME != null && !"".equals(CURR_INSTALL_LOG_NAME)){
                        String path = LOG_PATH_MEMORY_DIR + File.separator + CURR_INSTALL_LOG_NAME;
                        File file = new File(path);
                        if(!file.exists()){
                                return;
                        }
                        Log.d(TAG, "checkLog() ==> The size of the log is too big?");
                        if(file.length() >= MEMORY_LOG_FILE_MAX_SIZE){
                                Log.d(TAG, "The log's size is too big!");
                                new LogCollectorThread().start();
                        }
                }
        }
        
        /**
         * create log dir.
         */
        private void createLogDir() {
                File file = new File(LOG_PATH_MEMORY_DIR);
                boolean mkOk;
                if (!file.isDirectory()) {
                        mkOk = file.mkdirs();
                        if (!mkOk) {
                                mkOk = file.mkdirs();
                        }
                }
 
        }
 

        
        /**
         * check if file logs can be deleted.
         * @param createDateStr
         * @return
         */
        public boolean canDeleteSDLog(String createDateStr) {
                boolean canDel = false;
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, -1 * SDCARD_LOG_FILE_SAVE_DAYS);
                Date expiredDate = calendar.getTime();
                try {
                        Date createDate = sdf.parse(createDateStr);
                        canDel = createDate.before(expiredDate);
                } catch (ParseException e) {
                        Log.e(TAG, e.getMessage(), e);
                        canDel = false;
                }
                return canDel;
        }

        /**
         * delete expired log files.
         */
        private void deleteMemoryExpiredLog() {
                File file = new File(LOG_PATH_MEMORY_DIR);
                if (file.isDirectory()) {
                        File[] allFiles = file.listFiles();
                        for (File logFile : allFiles) {
                                String fileName = logFile.getName();
                                if (logServiceLogName.equals(fileName)) {
                                        continue;
                                }
                                String createDateInfo = getFileNameWithoutExtension(fileName);
                                if (canDeleteSDLog(createDateInfo)) {
                                        logFile.delete();
                                        Log.d(TAG, "delete expired log success,the log path is:"
                                                        + logFile.getAbsolutePath());

                                }
                        }
                }
        }
        

        
        /**
         * copy files.
         * @param source
         * @param target
         * @return
         */
        private boolean copy(File source, File target) {
                FileInputStream in = null;
                FileOutputStream out = null;
                try {
                        if(!target.exists()){
                                boolean createSucc = target.createNewFile();
                                if(!createSucc){
                                        return false;
                                }
                        }
                        in = new FileInputStream(source);
                        out = new FileOutputStream(target);
                        byte[] buffer = new byte[8*1024];
                        int count;
                        while ((count = in.read(buffer)) != -1) {
                                out.write(buffer, 0, count);
                        }
                        return true;
                } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage(), e);
                        recordLogServiceLog("copy file fail");
                        return false;
                } finally{
                        try {
                                if(in != null){
                                        in.close();
                                }
                                if(out != null){
                                        out.close();
                                }
                        } catch (IOException e) {
                                e.printStackTrace();
                                Log.e(TAG, e.getMessage(), e);
                                recordLogServiceLog("copy file fail");
                                return false;
                        }
                }
                
        }

        /**
         * Record base info of this log service, 
         * in Log.log
         * @param msg
         */
        private void recordLogServiceLog(String msg) {
                if (writer != null) {
                        try {
                                Date time = new Date();
                                writer.write(myLogSdf.format(time) + " : " + msg);
                                writer.write("\n");
                                writer.flush();
                        } catch (IOException e) {
                                e.printStackTrace();
                                Log.e(TAG, e.getMessage(), e);
                        }
                }
        }
        
        /**
         * @param fileName
         * @return
         */
        private String getFileNameWithoutExtension(String fileName){
                return fileName.substring(0, fileName.indexOf("."));
        }

        class ProcessInfo {
                public String user;
                public String pid;
                public String ppid;
                public String name;

                @Override
                public String toString() {
                        String str = "user=" + user + " pid=" + pid + " ppid=" + ppid
                                        + " name=" + name;
                        return str;
                }
        }
        class StreamConsumer extends Thread {
                InputStream is;
                List<String> list;

                StreamConsumer(InputStream is) {
                        this.is = is;
                }

                StreamConsumer(InputStream is, List<String> list) {
                        this.is = is;
                        this.list = list;
                }

                public void run() {
                        try {
                                InputStreamReader isr = new InputStreamReader(is);
                                BufferedReader br = new BufferedReader(isr);
                                String line = null;
                                while ((line = br.readLine()) != null) {
                                        if (list != null) {
                                                list.add(line);
                                        }
                                }
                        } catch (IOException ioe) {
                                ioe.printStackTrace();
                        }
                }
        }

        /**
         * log task receiver
         * 1. created new log collector thread
         * 2. check log size.
         * @author Administrator
         *
         */
        class LogTaskReceiver extends BroadcastReceiver{
                public void onReceive(Context context, Intent intent) {
                        String action = intent.getAction();
                        if(SWITCH_LOG_FILE_ACTION.equals(action)){
                                new LogCollectorThread().start();
                        }else if(MONITOR_LOG_SIZE_ACTION.equals(action)){
                                checkLogSize();
                        }
                }
        }
        
        class FileComparator implements Comparator<File>{
                public int compare(File file1, File file2) {
                        if(logServiceLogName.equals(file1.getName())){
                                return -1;
                        }else if(logServiceLogName.equals(file2.getName())){
                                return 1;
                        }
                        
                        String createInfo1 = getFileNameWithoutExtension(file1.getName());
                        String createInfo2 = getFileNameWithoutExtension(file2.getName());
                        
                        try {
                                Date create1 = sdf.parse(createInfo1);
                                Date create2 = sdf.parse(createInfo2);
                                if(create1.before(create2)){
                                        return -1;
                                }else{
                                        return 1;
                                }
                        } catch (ParseException e) {
                                return 0;
                        }
                }
        }
        
        @Override
        public void onDestroy() {
                super.onDestroy();
                recordLogServiceLog("LogService onDestroy");
                if (writer != null) {
                        try {
                                writer.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
                if (process != null) {
                        process.destroy();
                }
                
                unregisterReceiver(logTaskReceiver);
        }

}
